package com.imooc.miaosha.service;

import com.imooc.miaosha.dao.UserDao;
import com.imooc.miaosha.domain.User;
import com.imooc.miaosha.exception.GlobalException;
import com.imooc.miaosha.redis.RedisService;
import com.imooc.miaosha.redis.UserKey;
import com.imooc.miaosha.result.CodeMsg;
import com.imooc.miaosha.util.Md5Util;
import com.imooc.miaosha.util.UUIDUtil;
import com.imooc.miaosha.vo.LoginVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.Cookie;


import javax.servlet.http.HttpServletResponse;



@Service
public class UserService {

	public static final String COOKIE_TOKEN_NAME = "token";

	@Autowired
	UserDao UserDao;

	@Autowired
	RedisService redisService;

	public User getById(long id){
		return UserDao.getById(id);
	}

	public boolean login(HttpServletResponse response, LoginVo loginVo){
		if(loginVo == null){
			throw new GlobalException(CodeMsg.SERVER_ERROR);
		}
		String mobile = loginVo.getMobile();
		String password = loginVo.getPassword();

		User user = UserDao.getById(Long.parseLong(mobile));
		if(user == null){
			throw new GlobalException(CodeMsg.MOBILE_NOT_EXIST);
		}

		String salt = user.getSalt();
		String dbPass = user.getPassword();
		String md5Pass = Md5Util.formPass2DbPass(password, salt);
		if(!dbPass.equals(md5Pass)){
			throw new GlobalException(CodeMsg.PASSWORD_ERROR);
		}

		String token = UUIDUtil.uuid();
		addCookie(token, response, user);
		return true;
	}

	public User getByToke(String token, HttpServletResponse response) {
		if(StringUtils.isEmpty(token)){
			return null;
		}

		// 延长有效期
		User user = redisService.get(UserKey.token, token, User.class);
		if(user != null){
			addCookie(token, response, user);
		}
		return user;
	}

	private void addCookie(String token, HttpServletResponse response, User user){
		redisService.set(UserKey.token, token, user);
		Cookie cookie = new Cookie(COOKIE_TOKEN_NAME, token);
		cookie.setMaxAge(UserKey.token.expireSeconds());
		cookie.setPath("/");
		response.addCookie(cookie);
	}
	public User getByToke(String token) {
		if(StringUtils.isEmpty(token)){
			return null;
		}

		return redisService.get(UserKey.token, token, User.class);
	}
}
